package com.jeesite.modules.rt.web;

import java.util.Date;
import java.util.List;
import javax.servlet.http.HttpServletRequest;
import javax.servlet.http.HttpServletResponse;

import com.alibaba.fastjson.JSONObject;
import com.icecold.utils.QRCodeGenerator;
import com.icecold.utils.QRCodeGenerator2;
import com.jeesite.common.image.ZxingUtils;
import com.jeesite.common.lang.StringUtils;
import com.jeesite.modules.ic.entity.IcUser;
import com.jeesite.modules.ic.service.IcUserService;
import com.jeesite.modules.mo.entity.MoUserDevice;
import com.jeesite.modules.mo.service.MoUserDeviceService;
import com.jeesite.modules.rt.dao.RtDeviceDao;
import com.jeesite.modules.rt.entity.RtDeviceLine;
import com.jeesite.modules.rt.service.RtDeviceLineService;
import com.jeesite.modules.rt.service.RtErrorService;
import com.jeesite.modules.rt.tp.service.LingwuService;
import org.apache.shiro.authz.annotation.RequiresPermissions;
import org.springframework.beans.factory.annotation.Autowired;
import org.springframework.beans.factory.annotation.Value;
import org.springframework.stereotype.Controller;
import org.springframework.ui.Model;
import org.springframework.validation.annotation.Validated;
import org.springframework.web.bind.annotation.ModelAttribute;
import org.springframework.web.bind.annotation.PostMapping;
import org.springframework.web.bind.annotation.RequestMapping;
import org.springframework.web.bind.annotation.ResponseBody;

import com.jeesite.common.config.Global;
import com.jeesite.common.entity.Page;
import com.jeesite.common.web.BaseController;
import com.jeesite.modules.rt.entity.RtDevice;
import com.jeesite.modules.rt.service.RtDeviceService;

/**
 * 路由器设备Controller
 * @author 李寒冰
 * @version 2024-09-26
 */
@Controller
@RequestMapping(value = "${adminPath}/rt/rtDevice")
public class RtDeviceController extends BaseController {

	@Autowired
	private RtDeviceService rtDeviceService;

	@Value("${file.baseDir}")
	private String baseDir;

	@Value("${self.baseUrl}")
	private String selfBaseUrl;
    @Autowired
    private RtDeviceLineService rtDeviceLineService;
    @Autowired
    private MoUserDeviceService moUserDeviceService;
    @Autowired
    private IcUserService icUserService;
    @Autowired
    private RtErrorService rtErrorService;

	@Autowired
	private LingwuService lingwuService;

	@Autowired
	private RtDeviceDao rtDeviceDao;

	/**
	 * 获取数据
	 */
	@ModelAttribute
	public RtDevice get(String id, boolean isNewRecord) {
		return rtDeviceService.get(id, isNewRecord);
	}

	/**
	 * 生成二维码
	 */
	@RequiresPermissions("rt:rtDevice:view")
	@ResponseBody
	@RequestMapping(value = {"maskCode", ""})
	public String maskCode(RtDevice rtDevice, Model model) {
		rtDevice = rtDeviceService.get(rtDevice);
		String qrcode = rtDevice.getQrcode();
		if(StringUtils.isEmpty(qrcode)){
			String sn = rtDevice.getSn();
			RtDeviceLine deviceLineBySn = rtDeviceLineService.getDeviceLineBySn(sn);
//			ZxingUtils.encode2("https://www.zzlmvip.com?sn="+sn,400,400,baseDir+"/userfiles/qrcode/"+sn+".png");
			String[] arrBeizhu = new String[]{
					"品名:帮帮云盒",
					"MAC:"+deviceLineBySn.getMac(),
					"序列号:"+rtDevice.getXuliehao(),
			};
            try {
                QRCodeGenerator2.generateQRCode("https://www.zzlmvip.com?sn="+sn,arrBeizhu,baseDir+"/userfiles/qrcode/"+sn+".png");
            } catch (Exception e) {
                throw new RuntimeException(e);
            }
            rtDevice.setQrcode(selfBaseUrl+"/js/userfiles/qrcode/"+sn+".png");
			rtDeviceService.save(rtDevice);
		}

		return renderResult(Global.TRUE, text("！"),rtDevice.getQrcode());
	}

	/**
	 * 查询列表
	 */
	@RequiresPermissions("rt:rtDevice:view")
	@RequestMapping(value = {"list", ""})
	public String list(RtDevice rtDevice, Model model) {
//		rtDevice.setQrcode();
		model.addAttribute("rtDevice", rtDevice);
		return "modules/rt/rtDeviceList";
	}

	/**
	 * 查询列表
	 */
	@RequiresPermissions("rt:rtDevice:view")
	@RequestMapping(value = {"listWeishengchan", ""})
	public String listWeishengchan(RtDevice rtDevice, Model model) {
//		rtDevice.setQrcode();
		model.addAttribute("rtDevice", rtDevice);
		return "modules/rt/rtDeviceListWeiShengchan";
	}

	/**
	 * 查询列表
	 */
	@RequiresPermissions("rt:rtDevice:view")
	@RequestMapping(value = {"daililist", ""})
	public String daililist(RtDevice rtDevice, Model model) {
//		rtDevice.setQrcode();
		model.addAttribute("rtDevice", rtDevice);
		return "modules/rt/rtDeviceDailiShangList";
	}

	/**
	 * 二维码打印
	 */
	@RequiresPermissions("rt:rtDevice:view")
	@RequestMapping(value = {"qrcode", ""})
	public String qrcode(RtDevice rtDevice, Model model) {
		model.addAttribute("rtDevice", rtDevice);
		return "modules/rt/rtQrcode";
	}


	/**
	 * 查询列表数据
	 */
	@RequiresPermissions("rt:rtDevice:view")
	@RequestMapping(value = "listData")
	@ResponseBody
	public Page<RtDevice> listData(RtDevice rtDevice, HttpServletRequest request, HttpServletResponse response) {
		rtDevice.setPage(new Page<>(request, response));
		Page<RtDevice> page = rtDeviceService.findPage(rtDevice);
		for (RtDevice rt : page.getList()) {
			String sn = rt.getSn();
			MoUserDevice bySn = moUserDeviceService.findBySn(sn);
			RtDeviceLine deviceLineBySn = rtDeviceLineService.getDeviceLineBySn(sn);
			if(deviceLineBySn!=null){
				rt.setMac(deviceLineBySn.getMac());
			}

			if(bySn!=null){
				String userId = bySn.getUserId();
				IcUser icUser = icUserService.get(userId);
				rt.setIcUser(icUser);
			}
			//报警信息
			if(rtErrorService.getBySn(sn)!=null){
				rt.setIsError(true);
			}else{
				rt.setIsError(false);
			}

		}
		return page;
	}

	/**
	 * 查看编辑表单
	 */
	@RequiresPermissions("rt:rtDevice:view")
	@RequestMapping(value = "form")
	public String form(RtDevice rtDevice, Model model) {
		model.addAttribute("rtDevice", rtDevice);
		return "modules/rt/rtDeviceForm";
	}

	/**
	 * 批量改已生产
	 */
	@RequiresPermissions("rt:rtDevice:edit")
	@PostMapping(value = "saveYishengchan")
	@ResponseBody
	public String saveYishengchan(RtDevice rtDevice) {
		String id = rtDevice.getId();
		String[] split = id.split(",");
		for (int i = 0; i < split.length; i++) {
			String s = split[i];
			RtDevice rtDevice1 = rtDeviceService.get(s);
			rtDevice1.setShengchanStatus("2");
			rtDeviceService.save(rtDevice1);
		}


		return renderResult(Global.TRUE, text("保存路由器设备成功！"));
	}

	/**
	 * 保存数据
	 */
	@RequiresPermissions("rt:rtDevice:edit")
	@PostMapping(value = "save")
	@ResponseBody
	public String save(@Validated RtDevice rtDevice) {

		RtDevice rtDevice1 = rtDeviceService.get(rtDevice);
		//区域限制设置
		if(StringUtils.isNotEmpty(rtDevice.getQuyuxianzhi()) && !rtDevice.getQuyuxianzhi().equals(rtDevice1.getQuyuxianzhi())){
			Date setTime = rtDevice1.getSetTime();
			if(rtDevice1.getSetTime()!=null){
				if(System.currentTimeMillis()-setTime.getTime()<3*24*60*60*1000){
					return renderResult(Global.FALSE, text("三天内只可能设置一次区域限制！"));
				}
			}

			rtDevice.setSetTime(new Date());
			JSONObject b = lingwuService.setQuyuxianzhi(rtDevice1.getSn(), rtDevice.getQuyuxianzhi());
			if(b==null){
				return renderResult(Global.FALSE, text("设置失败！"));
			}else {
				if(b.getIntValue("code")!=200 || !b.getBoolean("success")){
					return renderResult(Global.FALSE, text(b.getString("message")));
				}
			}
		}
		rtDeviceService.save(rtDevice);



		return renderResult(Global.TRUE, text("保存路由器设备成功！"));
	}

	/**
	 * 保存数据
	 */
	@RequiresPermissions("rt:rtDevice:edit")
	@PostMapping(value = "setQuyushezhiForm")
	public String setQuyushezhiForm(RtDevice rtDevice, Model model) {
		model.addAttribute("rtDevice", rtDevice);
		return "modules/rt/rtDeviceSetQuyuxianzhi";
	}
	
	/**
	 * 删除数据
	 */
	@RequiresPermissions("rt:rtDevice:edit")
	@RequestMapping(value = "delete")
	@ResponseBody
	public String delete(RtDevice rtDevice) {
		rtDeviceService.delete(rtDevice);
		return renderResult(Global.TRUE, text("删除路由器设备成功！"));
	}
	
}